Page({
    data: {
      buildings: [],
      selectedBuilding: '',
      selectedBuildingId: null,
      roomList: [],
      selectedRoom: '',
      selectedRoomId: null,
      showBuildingPicker: false,
      showRoomPicker: false,
      dateOptions: [],
      selectedDateIndex: 0,
      rooms: [],
      loadMoreStatus: 'loading'
    },
  
    // 获取格式化后的日期
    getFormattedDate: function(daysToAdd) {
      const date = new Date();
      date.setDate(date.getDate() + daysToAdd);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
  
    // 更新日期选项
    updateDateOptions: function() {
      const dateOptions = [
        { label: '今天', value: this.getFormattedDate(0) },
        { label: '明天', value: this.getFormattedDate(1) },
        { label: '后天', value: this.getFormattedDate(2) }
      ];
      this.setData({ dateOptions });
    },
  
    onLoad: function() {
      this.getBuildings();
      this.updateDateOptions();
    },
  
    // 获取教学楼列表
    getBuildings: function() {
      const token = wx.getStorageSync('token');
      wx.request({
        url: `${getApp().globalData.baseUrl}/admin/buildings`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.data.code === 200) {
            const buildings = res.data.data.list.map(item => ({
              id: item.id,
              name: item.name
            }));
            this.setData({
              buildings: buildings
            });
          } else {
            wx.showToast({
              title: '获取教学楼失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    },
  
    // 获取教室列表
    getRooms: function(buildingId) {
      const token = wx.getStorageSync('token');
      wx.request({
        url: `${getApp().globalData.baseUrl}/admin/rooms`,
        method: 'GET',
        data: {
          buildingId: buildingId,
          page: 1,
          pageSize: 100 // 获取足够多的教室
        },
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.data.code === 200) {
            const rooms = res.data.data.list.map(item => ({
              id: item.id,
              name: item.name
            }));
            this.setData({
              roomList: rooms
            });
          } else {
            wx.showToast({
              title: '获取教室失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    },
  
    openBuildingPicker() {
      this.setData({ showBuildingPicker: true });
    },
  
    closeBuildingPicker() {
      this.setData({ showBuildingPicker: false });
    },
  
    openRoomPicker() {
      if (!this.data.selectedBuildingId) {
        wx.showToast({
          title: '请先选择教学楼',
          icon: 'none'
        });
        return;
      }
      this.setData({ showRoomPicker: true });
    },
  
    closeRoomPicker() {
      this.setData({ showRoomPicker: false });
    },
  
    selectBuilding(e) {
      const building = e.currentTarget.dataset.building;
      this.setData({
        selectedBuilding: building.name,
        selectedBuildingId: building.id,
        showBuildingPicker: false,
        selectedRoom: '', // 清空已选择的教室
        selectedRoomId: null
      });
      // 获取该教学楼的教室列表
      this.getRooms(building.id);
    },
  
    selectRoom(e) {
      const room = e.currentTarget.dataset.room;
      this.setData({
        selectedRoom: room.name,
        selectedRoomId: room.id,
        showRoomPicker: false
      });
    },
  
    selectDate(e) {
      const index = e.currentTarget.dataset.index;
      this.setData({ selectedDateIndex: index });
    },
  
    handleSearch() {
      const { selectedBuildingId, selectedRoomId, selectedDateIndex, dateOptions } = this.data;
      
      // 获取选择的日期
      const selectedDate = dateOptions[selectedDateIndex].value;
      
      // 检查是否选择了必要的条件
      if (!selectedBuildingId) {
        wx.showToast({
          title: '请选择教学楼',
          icon: 'none'
        });
        return;
      }

      if (!selectedRoomId) {
        wx.showToast({
          title: '请选择教室',
          icon: 'none'
        });
        return;
      }

      // 显示加载中
      wx.showLoading({
        title: '查询中...',
      });

      // 调用后端API
      const token = wx.getStorageSync('token');
      wx.request({
        url: `${getApp().globalData.baseUrl}/admin/empty-rooms/query`,
        method: 'GET',
        data: {
          buildingId: selectedBuildingId,
          roomId: selectedRoomId,
          date: selectedDate
        },
        success: (res) => {
          wx.hideLoading();
          console.log(res);
          if (res.data.code === 200) {
            // 更新空教室列表
            this.setData({
              rooms: res.data.data.list,
              loadMoreStatus: res.data.data.list.length === 0 ? 'noMore' : 'more'
            });
          } else {
            wx.showToast({
              title: res.data.message || '查询失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    },
  
    handleBook(e) {
      const room = e.currentTarget.dataset.room;
      // 处理预约逻辑
      console.log('预约教室:', room);
    },
  
    loadMore() {
      if (this.data.loadMoreStatus !== 'more') return;
      this.setData({ loadMoreStatus: 'loading' });
      setTimeout(() => {
        this.setData({ loadMoreStatus: 'noMore' });
      }, 1000);
    }
  });
  